<template>
  <view class="login-container">
    <!-- 提示登录图标 -->
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>

    <!-- 登录按钮 -->
    <button type="primary" class="btn-login" @click="getUserInfo">一键登录</button>

    <!-- 登录提示信息 -->
    <view class="tips-text">登录后尽享更多权益</view>
  </view>
</template>

<script>
import { mapMutations, mapState } from 'vuex'

export default {
  name: 'my-login',
  data() {
    return {}
  },
  computed: {
    ...mapState('m_user', ['redirectInfo'])
  },
  methods: {
    ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
    // 用户授权之后，获取用户的基本信息
    async getUserInfo() {
      // 调用获取用户基本信息的接口
      const [err, succ] = await uni.getUserProfile({ desc: '登录' }).catch(err => err)

      if (err && err.errMsg === 'getUserProfile:fail auth deny') {
        return uni.$showMsg('您取消了登录授权！')
      }

      this.updateUserInfo(succ.userInfo)
      
      this.getToken(succ)
    },
    async getToken(info) {
      // 获取 code 对应的值
      const [err, res] = await uni.login().catch(err => err)
      
      if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
      const query = {
        code: res.code,
        encryptedData: info.encryptedData,
        iv: info.iv,
        rawData: info.rawData,
        signature: info.signature
      }
      console.log(query.code)
      // 发起网络请求
      const { data: loginResult } = await uni.$http.post('/users/wxlogin', query)

      // 提示登录失败
      // if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')
      
      // 直接把 token 保存到 vuex 中
      // this.updateToken(loginResult.message.token)
      this.updateToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEyLCJpYXQiOjE1MjU0MDIyMjMsImV4cCI6MTUyNTQ4ODYyM30.g-4GtEQNPwT_Xs0Pq7Lrco_9DfHQQsBiOKZerkO-O-o')
      
      this.navigateBack()
    },
    navigateBack() {
      if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
        uni.switchTab({
          url: this.redirectInfo.from,
          complete: () => {
            this.updateRedirectInfo(null)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
.login-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 750rpx;
  background-color: #f8f8f8;
  overflow: hidden;

  &::after {
    position: absolute;
    bottom: 0;
    left: 0;
    transform: translateY(50%);
    content: '';
    display: block;
    width: 100%;
    height: 40px;
    background-color: #fff;
    border-radius: 100%;
  }

  .btn-login {
    width: 90%;
    background-color: #c00000;
    border-radius: 100px;
    margin: 15px 0;
  }

  .tips-text {
    font-size: 12px;
    color: gray;
  }
}
</style>
